<template>
  <div class="ebook" ref="ebook">
    <ebook-title></ebook-title>
    <ebook-reader></ebook-reader>
    <ebook-menu></ebook-menu>
    <ebook-bookmark></ebook-bookmark>
  </div>
</template>

<script>
// 引入子组件
import EbookReader from "../../components/ebook/EbookReader.vue"; // 阅读器主体
import EbookTitle from "../../components/ebook/EbookTitle.vue"; // 阅读器标题
import EbookMenu from "../../components/ebook/EbookMenu.vue"; // 阅读器下面的菜单
import EbookBookmark from "../../components/ebook/EbookBookmark"; // 书签
import { getReadTime, saveReadTime } from "../../utils/localStorage"; //阅读时间本地
import { ebookMixin } from "../../utils/mixin";

export default {
  mixins: [ebookMixin],
  data() {
    return {};
  },
  watch: {
    offsetY(v) {
      // 监听下拉的变化
      // 当菜单栏出现时 不允许下拉
      // 且 当分页未完成时 不予许下拉
      if (!this.menuVisible && this.bookAvailable) {
        if (v > 0) {
          this.move(v);
        } else if (v === 0) {
          this.restore();
        }
      }
    }
  },
  methods: {
    startLoopReadTime() {
      // 记录阅读时间
      let readTime = getReadTime(this.fileName);
      if (!readTime) {
        readTime = 0;
      }
      this.task = setInterval(() => {
        readTime++;
        if (readTime % 30 === 0) {
          saveReadTime(this.fileName, readTime); // 每 30s 记录一次 本地
        }
      }, 1000);
    },
    move(v) {
      // 改变定位的 top 值
      this.$refs.ebook.style.top = v + "px";
    },
    restore() {
      // 还原 top 值
      this.$refs.ebook.style.top = 0;
      this.$refs.ebook.style.transition = "all .2s linear";
      // 当触发 过度后 要移出掉 因为在快速下拉、松手后 都会触发 0.2 秒的过度 显得不流畅
      setTimeout(() => {
        this.$refs.ebook.style.transition = "";
      }, 200);
    }
  },
  mounted() {
    this.startLoopReadTime();
  },
  beforeDestroy() {
    // 销毁之前 清除定时器
    if (this.task) clearInterval(this.task);
  },
  components: {
    EbookReader,
    EbookTitle,
    EbookMenu,
    EbookBookmark
  }
};
</script>

<style lang='scss' scoped>
@import "../../assets/styles/global.scss";
.ebook {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>
